package net.starwifi.duobao.service.impl;

import net.starwifi.duobao.SettingUtils;
import net.starwifi.duobao.entity.Setting;
import net.starwifi.duobao.service.SettingService;
import net.starwifi.duobao.service.WXCoreService;
import net.starwifi.duobao.utils.wx.WXCoreAPI;
import net.starwifi.duobao.wx.WXTicketResponse;
import net.starwifi.duobao.wx.WXTokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * Created by Administrator on 2016/3/14 0014.
 */
@Service
public class WXCoreServiceImpl implements WXCoreService {

    @Autowired
    SettingService settingService;


    @Override
    public String getToken() {
        Setting setting=settingService.findByCode("wxToken");
        String token=setting.getConfigValue();
        if(new Date().getTime()-setting.getModifyDate().getTime()>1000*60*30){
            String appId=SettingUtils.get("wx_appid");
            String appSecret=SettingUtils.get("wx_appsecret");
            String jsonStr=WXCoreAPI.getToken(appId, appSecret);
            WXTokenResponse wxResponse= WXTokenResponse.parseStr(jsonStr);//解析JSON
            token=wxResponse.getAccess_token();
            setting.setConfigValue(token);
            settingService.update(setting);
        }
        return token;
    }

    @Override
    public String getJsTicket() {
        Setting setting=settingService.findByCode("wxTicket");
        String jsTicket=setting.getConfigValue();
        if(new Date().getTime()-setting.getModifyDate().getTime()>1000*60*30){
            String jsonStr=WXCoreAPI.getJsTicket(getToken(), "jsapi");
            WXTicketResponse wxTicketResponse=WXTicketResponse.parseStr(jsonStr);
            jsTicket=wxTicketResponse.getTicket();
            setting.setConfigValue(jsTicket);
            settingService.update(setting);
        }
        return jsTicket;
    }

//    @Override
//    public   String  getSign(String jsapi_ticket, String url, String nonce_str,String timestamp){
//        Map<String, String> ret = new HashMap<String, String>();
//        String str;
//        String signature = "";
//        //注意这里参数名必须全部小写，且必须有序
//        str = "jsapi_ticket=" + jsapi_ticket +
//                "&noncestr=" + nonce_str +
//                "&timestamp=" + timestamp +
//                "&url=" + url;
//        try
//        {
//            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
//            crypt.reset();
//            crypt.update(str.getBytes("UTF-8"));
//            signature = byteToHex(crypt.digest());
//        }
//        catch (NoSuchAlgorithmException e)
//        {
//            e.printStackTrace();
//        }
//        catch (UnsupportedEncodingException e)
//        {
//            e.printStackTrace();
//        }
//        String[] paramArr = new String[] { "jsapi_ticket=" + jsapi_ticket,
//                "timestamp=" + timestamp, "noncestr=" + nonce_str, "url=" + url };
//        Arrays.sort(paramArr);
//// 将排序后的结果拼接成一个字符串
//        String content = paramArr[0].concat("&"+paramArr[1]).concat("&"+paramArr[2])
//                .concat("&"+paramArr[3]);
//        System.out.println("拼接之后的content为:"+content);
//        signature=sha1(content).toString();

//        System.out.println("签名1:" + signature);
//        // System.out.println("签名2:"+  SHA1Util.encode(string1) );
//        return signature;
//
//    }
//    private static String byteToHex(final byte[] hash) {
//        Formatter formatter = new Formatter();
//        for (byte b : hash)
//        {
//            formatter.format("%02x", b);
//        }
//        String result = formatter.toString();
//        formatter.close();
//        return result;
//    }

    public Map<String, String> getSign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
